package com.mmm.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.mmm.user.dao.UserDao;
import com.mmm.user.dto.TokenDto;
import com.mmm.user.entity.User;
import com.mmm.user.service.JwtService;
import com.mmm.user.service.TokenService;
import com.mmm.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.text.MessageFormat;
import java.util.Date;

/**
 * @email 1067559930@qq.com
 * @author: One
 * @date: 2022/02/28
 * @time: 16:21
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.appSecret}")
    private String appSecret;
    @Value("${wx.code2Session}")
    private String makeOpenId;

    @Resource
    private UserDao userDao;

    @Resource
    private UserService userService;

    @Autowired
    private JwtService jwtService;

    @Override
    public String code2Session(User user) {
//        请求微信官方获取openId
        String format = MessageFormat.format(this.makeOpenId, this.appid, this.appSecret, user.getOpenId());
        RestTemplate restTemplate = new RestTemplate();
        String request = restTemplate.getForObject(format, String.class);
//        解析openid
        JSONObject object = JSON.parseObject(request);
        String openId = object.get("openid").toString();
        user.setOpenId(openId);
        return this.register(user);
    }


    private String register(User user) {
        User find = userDao.findByOpenId(user.getOpenId());
//        如果用户不存在则注册并放回token
        if (find == null) {
            Date date = new Date();
            user.setBan(1);
            user.setGrade(5);
            user.setCreateTime(date);
            user.setUpdateTime(date);

            User insert = userService.insert(user);
//            int insert = userDao.insert(user);
            if (insert.getOpenId()!=null) {
                return jwtService.makeToken(user.getId(), user.getGrade(),user.getUniversityId());
            }
        }
//        用户存查看是否被封号
        if (find.getBan() != 1) {
            throw new RuntimeException("该用户已被封号");
        }
//      放回token
        return jwtService.makeToken(find.getId(), find.getGrade(),find.getUniversityId());

    }
}
